﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using LinqToLfsWorld;

namespace LibraryTest
{
	/// <summary>
	/// Summary description for CachingTests
	/// </summary>
	[TestClass]
	public class CachingTests
	{
		private static LfsWorldContext _lfswContext = null;

		public CachingTests()
		{
		}

		private TestContext testContextInstance;

		/// <summary>
		///Gets or sets the test context which provides
		///information about and functionality for the current test run.
		///</summary>
		public TestContext TestContext
		{
			get
			{
				return testContextInstance;
			}
			set
			{
				testContextInstance = value;
			}
		}

		#region Additional test attributes
		//
		// You can use the following additional attributes as you write your tests:
		//
		// Use ClassInitialize to run code before running the first test in the class
		[ClassInitialize()]
		public static void MyClassInitialize(TestContext testContext) 
		{
			_lfswContext = new LfsWorldContext();
		}
		
		// Use ClassCleanup to run code after all tests in a class have run
		[ClassCleanup()]
		public static void MyClassCleanup() 
		{
			_lfswContext.Dispose();
		}

		//
		// Use TestInitialize to run code before running each test 
		// [TestInitialize()]
		// public void MyTestInitialize() { }
		//
		// Use TestCleanup to run code after each test has run
		// [TestCleanup()]
		// public void MyTestCleanup() { }
		//
		#endregion

		[TestMethod]
		public void CachePropertiesTest()
		{
			_lfswContext.CachingEnabled = false;
			_lfswContext.CacheTime = TimeSpan.FromSeconds(30);

			Assert.AreEqual(false, _lfswContext.CachingEnabled);
			Assert.AreEqual(TimeSpan.FromSeconds(30), _lfswContext.CacheTime);

			_lfswContext.CachingEnabled = true;
		}

		int requestCacheText_Index = 0;

		[TestMethod]
		public void RequestCacheTest()
		{
			_lfswContext.CachingEnabled = true;
			_lfswContext.PremiumPubstatAccess = false; // make sure this is off to demonstrate that the caching works.
			_lfswContext.RequestMade += new LfsRequestHandler(RequestCacheTest_RequestMade);

			var statsQuery = from stat in _lfswContext.RacerStats
							 where stat.RacerName == "elkdanger"
							 select stat;

			for (int i = 0; i < 10; i++)
			{
				requestCacheText_Index = i;

				// If caching wasn't enabled, we would get an exception the next time we hit the server
				// because of the 5-second tarpit.
				var stat = statsQuery.ToList();
			}

			_lfswContext.RequestMade -= new LfsRequestHandler(RequestCacheTest_RequestMade);
		}

		void RequestCacheTest_RequestMade(object sender, LfsWorldResponse response)
		{
			if (requestCacheText_Index == 0)
			{
				Assert.AreEqual(false, response.FromCache);
			}
			else
			{
				Assert.AreEqual(true, response.FromCache);
			}
		}
	}
}
